#include <stdio.h>
#include <signal.h>
#include "ax_common.h"
#include "global.h"
#include "config.h"

extern void run_test_case();

void sig_hup(int signo)
{
	engine_abort("catch SIGHUP");
}

void sig_term(int signo)
{
	engine_abort("catch SIGTERM");
}

void init_signal()
{
	signal(SIGTERM, sig_term);
	signal(SIGINT, sig_term);
	signal(SIGHUP, sig_hup);
}

int main(int argc, char ** argv)
{
	char ch;	

	debug_msg("game server started");
	//init shell args
	while ((ch = getopt(argc, argv, "td:c")) != -1)
	{
		switch(ch)
		{
		//run unit test
		case 't':
			run_test_case();
			return 0;
		//run program, definite config file
		case 'c':
			if (GConf::reload_config(optarg) != 0) {
				return 0;  //config file error
			}
			break;
		default:
			break;
		}

	}	

	init_signal();	
	init_net();
	connect_netd();
	dispatch();

	debug_msg("game server exit normally.");
	return 0;
}

void debug_msg(const char* fmt, ...)
{
	static char file[1024];
	va_list args;
	va_start(args, fmt);
	sprintf(file, "%s/%s", GConf::log_path, GConf::log_debug_name);
	ax_vlogf(file, fmt, args);
	vprintf(fmt, args);
	printf("\n");
	va_end(args);
}

//engine abort
void engine_abort(const char* reason)
{
	debug_msg("GAME ABORT!! reason: %s", reason);	
	exit(-1);
}
